using System;
using System.ComponentModel;
using System.Reflection;

namespace Domain.RBAC.Extensions
{
    /// <summary>
    /// 枚举扩展方法
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// 获取枚举的Description特性值
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <returns>Description特性的值，如果没有则返回枚举名称</returns>
        public static string GetDescription(this Enum value)
        {
            if (value == null)
                return string.Empty;

            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (string.IsNullOrEmpty(name))
                return string.Empty;

            FieldInfo? field = type.GetField(name);
            if (field == null)
                return name;

            DescriptionAttribute? attribute = field.GetCustomAttribute<DescriptionAttribute>();
            return attribute?.Description ?? name;
        }

        /// <summary>
        /// 将整数值转换为对应的枚举描述
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="value">整数值</param>
        /// <returns>枚举描述文本</returns>
        public static string ToEnumDescription<T>(this int value) where T : Enum
        {
            if (Enum.IsDefined(typeof(T), value))
            {
                T enumValue = (T)Enum.ToObject(typeof(T), value);
                return enumValue.GetDescription();
            }
            return value.ToString();
        }

        /// <summary>
        /// 判断枚举值是否已定义
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="value">要检查的值</param>
        /// <returns>是否已定义</returns>
        public static bool IsDefinedEnum<T>(this int value) where T : Enum
        {
            return Enum.IsDefined(typeof(T), value);
        }
    }
}


